package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     *
     * @param session  登录成功将员工id存到session中
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpSession session, @RequestBody Employee employee) {
        //long id = Thread.currentThread().getId();
        //log.info("线程id:{}",id);
        Employee emp = employeeService.findOne(employee);
        if (emp != null) { //判断用户名与密码是否存在
            if (emp.getStatus() == 0) { //表示员工已禁用
                return R.error("账号已禁用");
            }
            session.setAttribute("employee", emp.getId());
            return R.success(emp);
        }
        return R.error("登录失败");
    }

    /**
     * 分页展示
     *
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page<Employee>> page(int page, int pageSize, String name) {
        log.info("分页查询参数:page={},pageSize={},name={}", page, pageSize, name);
        Page<Employee> employeePage = employeeService.findEmployeePage(page, pageSize, name);
        return R.success(employeePage);
    }

    /**
     * 退出登录
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        //删除session属性
        //request.getSession().removeAttribute("employee");
        //删除session对象
        request.getSession().invalidate();
        log.info("用户已退出登录");
        return R.success("退出成功");
    }

    /**
     * 修改员工信息
     * 修改状态--禁用启用
     *
     * @return
     */
    @PutMapping
    public R<String> updateById(@RequestBody Employee employee) {
        employeeService.updateById(employee);
        return R.success("修改成功");
    }

    /**
     * 根据id查询,修改数据回显
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> findById(@PathVariable long id) {
        Employee emp = employeeService.getById(id);
        return R.success(emp);
    }

    /**
     * 新增---添加员工
     *
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> add(@RequestBody Employee employee) {
        employeeService.save(employee);
        return R.success("添加成功");
    }
}
